package com.lmt.service.impl;

import com.lmt.base.BaseService;
import com.lmt.base.ResultData;
import com.lmt.entity.LoginLog;
import com.lmt.entity.search.LoginLogSearch;
import com.lmt.repository.LoginLogRepository;
import com.lmt.service.LoginLogService;
import com.lmt.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@Service("LoginLogServiceImpl")
public class LoginLogServiceImpl extends BaseService implements LoginLogService {

	private final LoginLogRepository loginLogRepository;

	@Autowired
	public LoginLogServiceImpl(LoginLogRepository loginLogRepository) {
		this.loginLogRepository = loginLogRepository;
	}

	@Override
	public void save(LoginLog loginLog) {
		this.loginLogRepository.save(loginLog);
	}

	@Override
	public ResultData search(LoginLogSearch loginLogSearch) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT ll.password_error_time - 1 AS passwordErrorTime, ");
		sql.append("ll.gmt_create AS gmtCreate, ");
		sql.append("ll.gmt_modified AS gmtModified, ");
		sql.append("ui.user_name AS userName, ");
		sql.append("(SELECT dd.designation FROM digital_dictionary AS dd WHERE dd.code = ll.result) ");
		sql.append("AS result, ");
		sql.append("(SELECT dd.designation FROM digital_dictionary AS dd WHERE dd.code = ll.status) ");
		sql.append("AS status, ");
		sql.append("(SELECT dd.designation FROM digital_dictionary AS dd WHERE dd.code = ui.user_type) ");
		sql.append("AS userType ");
		sql.append("FROM login_log AS ll, user_info AS ui WHERE ui.id = ll.user_id ");
		if (!StringUtils.isEmpty(loginLogSearch.getKeyword())) {
			sql.append("AND ui.user_name LIKE ? ");
			loginLogSearch.setParamsCount(1);
		}
		sql.append("ORDER BY ll.gmt_create DESC ");
		Map result = this.paginationSearch(sql, loginLogSearch);
		return ResultUtil.newSuccess("日志查询成功", result);
	}
}
